var countProductLine = 0;
var inputStyle = "width:90%; margin-bottom: 0px; padding: 0px; text-align: center;";
var oldQuantity;

$('.selectedCustomer').live("click", function() {
	  var tr = $(this).closest("tr");
	  var tds = $(tr).find("td");
	  $('#phoneNumber').attr("value", $(tds[3]).text());
	  $('#customerEmailAddress').attr("value", $(tds[2]).text());
	  $('#customerFirstName').attr("value", $(tds[0]).text());
	  $('#customerLastName').attr("value", $(tds[1]).text());
	  $('#billingAdress').attr("value", $(tds[6]).text());
	  $('#billingState').attr("value", $(tds[7]).text());
	  $('#billingCity').attr("value", $(tds[8]).text());
	  
	  $('#shippingFirstName').attr("value", $(tds[9]).text());
	  $('#shippingLastName').attr("value", $(tds[10]).text());
	  $('#shippingAddress').attr("value", $(tds[11]).text());
	  $('#shippingState').attr("value", $(tds[12]).text());
	  $('#shippingCity').attr("value", $(tds[13]).text());
	  $('#customerId').attr("value", $(tds[14]).text());
	  
	  $('#closeModal').click();
});

function addProductHandler(){
	$('#addProduct').click(function(){
		var productName = $('#addProdName').val();
		var quantity = $('#addQuantity').val();
		if(!productName){
			$('#addingError').text("Thiếu tên sản phẩm");
			return false;
		}
		
		if(!quantity){
			$('#addingError').text("Thiếu số lượng sản phẩm");
			return false;
		}
		
		if( !(quantity > 0 && Math.floor(quantity) == quantity && $.isNumeric(quantity)) ){
			$('#addingError').text("Số lượng phải là số lớn hơn không");
			return false;
		}
		
		countProductLine ++;
		var price = $('#showPrice').val();
		var total = price.replace(/,/g,"") * quantity;
		var tr = '<tr><td colSpan="2">' + productName + '</td><td><input type="text" name="quantityAdd" style="' + inputStyle + '" class="editQtt" value="' 
			+ quantity + '" /></td><td>'+price+'</td><td>'
			+ total + '</td><td><a class="recalculateProd">Tính</a>&nbsp<a class="removeProd">Xóa</a>'
			+'<input type="hidden" name="productNameAdd" value="'+productName+'"/></td></tr>';
			
		$(tr).insertBefore($('#subtotalTd'));
		
		$('.totalClass').show();
		calculateTotal();
		
		$('#addProdName').val("");
		$('#addQuantity').val("1");
		$('#showPrice').val('');
	});
	
	$('#addProductImport').click(function(){
		var productName = $('#addProdImportName').val();
		var quantity = $('#addQuantity').val();
		if(!productName){
			$('#addingError').text("Thiếu tên sản phẩm");
			return false;
		}
		
		if(!quantity){
			$('#addingError').text("Thiếu số lượng sản phẩm");
			return false;
		}
		
		if( !(quantity > 0 && Math.floor(quantity) == quantity && $.isNumeric(quantity)) ){
			$('#addingError').text("Số lượng phải là số lớn hơn không");
			return false;
		}
		
		countProductLine ++;
		var price = $('#showPrice').val();
		var total = price.replace(/,/g,"") * quantity;

		var tr = '<tr><td colSpan="2">' + productName + '</td><td><input type="text" name="quantityAdd" style="' + inputStyle + '" class="editQtt" value="' 
			+ quantity + '" /></td><td>'+price+'</td><td>'
			+ total + '</td><td><a class="recalculateProd">Tính</a>&nbsp<a class="removeProd">Xóa</a>'
			+'<input type="hidden" name="productNameAdd" value="'+productName+'"/></td></tr>';
			
		$(tr).insertBefore($('#subtotalTd'));
		
		$('.totalClass').show();
		calculateTotal();
		
		$('#addProdImportName').val("");
		$('#addQuantity').val("1");
		$('#showPrice').val('');
	});
}

$('.removeProd').live("click", function(){
	var tr = $(this).closest("tr");
	$(tr).remove();
	countProductLine --;
	if(countProductLine == 0){
		$('.totalClass').hide();
	} else {
		calculateTotal();
	}
});


$('.recalculateProd').live("click", function(){
	var tr = $(this).closest("tr");
	var tds = $(tr).find("td");
	
	var price = $(tds[2]).text().replace(/,/g,"");
	var quantity = $($(tds[1]).find("input")[0]).val();
	$(tds[3]).text(price * quantity);
	$(tds[3]).formatCurrency({ colorize: true, negativeFormat: '-%s%n', roundToDecimalPlace: -1, eventOnDecimalsEntered: true, symbol: ''});

	calculateTotal();
});

function calculateTotal(){
	var trs = $('#productsList').children("tr");
	var total = 0;
	for(var i = 0; i < trs.length - 2 ; i++){
		var tds = $(trs[i]).find("td");
		var quantity = $($(tds[1]).find("input")[0]).val();
		var price = $(tds[2]).text().replace(/,/g,"") ;
		if( (quantity > 0 && Math.floor(quantity) == quantity && $.isNumeric(quantity)) ){
			if( (price > 0 && Math.floor(price) == price && $.isNumeric(price)) ){
				total += price * quantity;
			}
		}
	}
	
	$('#subtotal').text(total);
	$('#total').text(total);
	$('#subtotal').formatCurrency({ colorize: true, negativeFormat: '-%s%n', roundToDecimalPlace: -1, eventOnDecimalsEntered: true, symbol: ''});
	$('#total').formatCurrency({ colorize: true, negativeFormat: '-%s%n', roundToDecimalPlace: -1, eventOnDecimalsEntered: true, symbol: ''});

}

$('.editQtt').live("keydown", function(event){
	if ( event.which == 13 ) {
		return false;
	}
});

$('.editQtt').live("change", function(event){
	if(!isInteger($(this).val())){
		$(this).val(oldQuantity);
		return false;
	}
	
	var tr = $(this).closest("tr");
	var recal = $(tr).find(".recalculateProd");
	$(recal[0]).click();
});

$('.editQtt').live("click", function(event){
	oldQuantity = $(this).val();
});


$('.tab-content').find("input").each(function(){
	$(this).live("keydown", function(event){
		if ( event.which == 13 ) {
			return false;
		}
	});
});


function isInteger(number){
	return number > 0 && Math.floor(number) == number && $.isNumeric(number);
}

function sendInvoice(orderId){

	$.ajax({
		  type: 'GET',
		  url: '<c:url value="/admin/orders/sendInvoice.html"/>?id=' + orderId,
		  dataType: 'json',
		  success: function(response){
				var status = response.response.status;
				var data = response.response.data;
				//console.log(status);
				if(status==0 || status ==9999) {
					$(".alert-success").show();
				} else {
					$(".alert-error").show();
				}
				$('.sm').hideLoading();
		  },
		    error: function(xhr, textStatus, errorThrown) {
		  	alert('error ' + errorThrown);
		  	$('.sm').hideLoading();
		  }
	
	});
}

function resetMessages() {
	$(".alert-error").hide();
	$(".alert-success").hide();
}

function sendDownloadEmail(orderId){

	$.ajax({
		  type: 'GET',
		  url: '<c:url value="/admin/orders/sendDownloadEmail.html"/>?id=' + orderId,
		  dataType: 'json',
		  success: function(response){
				var status = response.response.status;
				var data = response.response.data;
				//console.log(status);
				if(status==0 || status ==9999) {
					$(".alert-success").show();
				} else {
					$(".alert-error").show();
				}
				$('.sm').hideLoading();
		  },
		    error: function(xhr, textStatus, errorThrown) {
		  	alert('error ' + errorThrown);
		  	$('.sm').hideLoading();
		  }
	
	});
}


function loadCustomerByPhone(){
	var phone = $('#phoneNumber').val();
	$.ajax({
	  type: 'GET',
	  dataType: "json",
	  url: '<c:url value="/admin/orders/customerInfo.html"/>?phone=' + phone,
	  success: function(response){
		  var status = response.response.status;
		  var data = response.response.data;
			if(status==0 || status ==9999) {
				$('#customersModal').modal();
				$(".alert-success").show();
			} else {
				$(".alert-error").show();
				$("#waiting").css("display","none");
			}
			var customers = data;
			if(customers==null || customers.length==0){
				$('#transactionList').append('<tr><td colspan="6">Not found</td></tr>');
			}
			for(i=0;i<customers.length;i++) {
				var tr = '<tr><td>' + customers[i].bfirstName + '</td><td>' + customers[i].blastName + '</td><td>' 
					+ customers[i].email + '</td><td>' + customers[i].phone + '</td><td>' 
					+ customers[i].bstreet + ' - ' + customers[i].bCity + '</td><td>'
					+ customers[i].dstreet + ' - ' + customers[i].dCity + '</td><td style="display:none;">'
					+ customers[i].bstreet + '</td><td style="display:none;">'
					+ customers[i].bState + '</td><td style="display:none;">'
					+ customers[i].bCity + '</td><td style="display:none;">'
					+ customers[i].dfirstName + '</td><td style="display:none;">'
					+ customers[i].dlastName + '</td><td style="display:none;">'
					+ customers[i].dstreet + '</td><td style="display:none;">'
					+ customers[i].dState + '</td><td style="display:none;">'
					+ customers[i].dCity + '</td><td style="display:none;">'
					+ customers[i].customerId + '</td><td><button class="selectedCustomer">Select</button></td>';
				$('#transactionList').append(tr);
			}			
	  }
	});
	$("#waiting").css("display","none");
}

function loadCustomerByEmail(){
	var email = $('#customerEmailAddress').val();
	$.ajax({
	  type: 'GET',
	  dataType: "json",
	  url: '<c:url value="/admin/orders/customerInfo.html"/>?email=' + email,
	  success: function(response){
		  var status = response.response.status;
		  var data = response.response.data;
			if(status==0 || status ==9999) {
				$('#customersModal').modal();
				$(".alert-success").show();
			} else {
				$(".alert-error").show();
				$("#waiting").css("display","none");
			}
			var customers = data;
			if(customers==null || customers.length==0){
				$('#transactionList').append('<tr><td colspan="6">Not found</td></tr>');
			}
			for(i=0;i<customers.length;i++) {
				var tr = '<tr><td>' + customers[i].bfirstName + '</td><td>' + customers[i].blastName + '</td><td>' 
					+ customers[i].email + '</td><td>' + customers[i].phone + '</td><td>' 
					+ customers[i].bstreet + ' - ' + customers[i].bCity + '</td><td>'
					+ customers[i].dstreet + ' - ' + customers[i].dCity + '</td><td style="display:none;">'
					+ customers[i].bstreet + '</td><td style="display:none;">'
					+ customers[i].bState + '</td><td style="display:none;">'
					+ customers[i].bCity + '</td><td style="display:none;">'
					+ customers[i].dfirstName + '</td><td style="display:none;">'
					+ customers[i].dlastName + '</td><td style="display:none;">'
					+ customers[i].dstreet + '</td><td style="display:none;">'
					+ customers[i].dState + '</td><td style="display:none;">'
					+ customers[i].dCity + '</td><td style="display:none;">'
					+ customers[i].customerId + '</td><td><button class="selectedCustomer">Select</button></td>';
				$('#transactionList').append(tr);
			}			
	  }
	});
	$("#waiting").css("display","none");
}

$.fn.addItems = function(div, data, defaultValue) {
	//console.log('Populating div ' + div + ' defaultValue ' + defaultValue);
	var selector = div + ' > option';
	var defaultExist = false;
    $(selector).remove();
        return this.each(function() {
            var list = this;
            $.each(data, function(index, itemData) {
            	//console.log(itemData.code + ' ' + defaultValue);
            	if(itemData.code==defaultValue) {
            		defaultExist = true;
            	}
                var option = new Option(itemData.name, itemData.code);
                list.add(option);
            });
            if(defaultExist && (defaultValue!=null && defaultValue!='')) {
           	 	$(div).val(defaultValue);
            }
     });
};
